<template>
  <div class="page_staffRollCall">
    <van-nav-bar :title="itemObj.title" left-arrow @click-left="$router.back()" />
    <job-item-for-recruit
      :jobItem="needObj"
      :keyWord="'recruitmentManagement'"
      :routeName="'recruitStaffList'"
      :searchNameType="'0'"
    ></job-item-for-recruit>

    <van-divider :style="{color: '#1989fa', borderColor: '#1989fa', padding: '0 60px', fontWeight: 'bolder'}">
      {{ '以下' + itemObj.title }}
    </van-divider>

    <div class="codeDiv" v-if="itemObj.id !== '5'">
      <van-cell :title="itemObj.title + '码'" :value="verify_code" size="large">
        <template #right-icon>
          <van-icon name="replay" @click="replay()" class="replay-icon">设置</van-icon>
        </template>
      </van-cell>
      <div style="margin: 16px;">
        <van-button class="useBtn" @click="useCode()" :disabled="!verify_code">确定使用</van-button>
      </div>
    </div>
    <div class="channelBox" v-if="itemObj.id == '5'">
      <div class="list">
        <van-radio-group v-model="hannelRadio">
          <div class="item" v-for="(item, index) in listData" :key="index">
            <van-radio :name="item.id"></van-radio>
            <div class="left">
              <div class="top">
                <div class="text">渠道公司：{{ item.channel_name }}</div>
              </div>
              <div class="bottom">
                <div class="text">渠道人：{{ item.channel_emp_name }}</div>
              </div>
              <div class="bottom">
                <div class="label"></div>
                <div class="text">招聘员工人数：{{ item.count }}</div>
              </div>
            </div>
            <div class="right">
              <van-button plain type="warning" size="mini" @click="check(item)">查看</van-button>
            </div>
          </div>
        </van-radio-group>
      </div>
    </div>
    <van-action-sheet
      v-model="showAction"
      :actions="actions"
      cancel-text="取消"
      close-on-click-action
      @select="onSelect"
    />
  </div>
</template>

<script>
import copylink from '@/assets/img/myCompany/copylink.png'
import qrcodeIcon from '@/assets/img/myCompany/qrcode.png'
import {reqGetBdCode, reqUpdateBdCode} from '../../../api/myCompany'
import {Dialog, Toast} from 'vant'
import {obj} from '../../../constants/comUtils'
import jobItemForRecruit from './common/jobItemForRecruit'
import {mapGetters} from 'vuex'
export default {
  name: 'staffRollCall',
  components: {
    jobItemForRecruit
  },
  computed: {
    ...mapGetters(['allUserInfo'])
  },
  data() {
    const needJobObj = this.$route.query.data
    return {
      hannelRadio: '',
      listData: [],
      itemObj: {},
      needObj: needJobObj ? JSON.parse(needJobObj) : {},
      showAction: false,
      actions: [{name: '短信发送'}, {name: '平台发送'}],
      verify_code: '',
      type: this.$route.query.type,
      typeList: ['qudaocode','baodaocode', 'jiesongcode', 'daoqicode', 'fxscode', 'peixuncode', 'hetongcode'],
      isCanUseCode: false,
      qrCodeTypeObj: {
        '5': '渠道来源',
        '6': '报到点名',
        '7': '接送点名',
        '8': '到用企点名',
        '9': '分宿舍点名',
        '10': '培训点名',
        '11': '合同协议'
      }
    }
  },

  async created() {
    if (this.$route.query.itemObj && this.$route.query.data) {
      this.itemObj = JSON.parse(this.$route.query.itemObj)
    } else {
      Toast.fail('获取参数异常,请重新操作。')
      this.$router.back()
    }
    if (this.itemObj.id == '5') {
      const {data: dataTrue} = await this.$api.company.getinfos({
        company_id: this.allUserInfo.company_id,
        JobID: this.needObj.id,
        is_enbale: true
      })
      this.listData = dataTrue.items
      if (this.listData.length === 0) {
        Dialog.alert({
          title: '温馨提示',
          message: `当前无可用的线下报名渠道来源，请前往设置`,
          messageAlign: 'left',
          theme: 'round-button',
          confirmButtonText: '前往设置'
        }).then(() => {
          this.$router.push({
            path: '/myCompany/channel',
            query: {
              companyId: this.allUserInfo.company_id
            }
          })
        })
      }
    }
  },

  mounted() {
    if (this.needObj.id && this.type) {
      const param = {
        jobId: this.needObj.id,
        type: this.typeList[this.type]
      }
      this._getCode(param)
    }
  },

  methods: {
    check(item) {
      const {job_id, data} = this.$route.query
      this.$router.push({
        path: '/myCompany/recruitStaffList',
        query: {
          jobInfoId: job_id,
          advaceInfoType: 2,
          data,
          searchVal: item.channel_emp_name
        }
      })
    },
    async _getCode(param) {
      const resp = await reqGetBdCode(param)
      if (resp.code === 200) {
        if (resp.data) {
          this.verify_code = resp.data.baodaocode
          this.isCanUseCode = true
        } else {
          // Toast(`还没有设置${this.qrCodeTypeObj[this.itemObj.id]}码，请先设置!`);
          if(this.type == 0){
            
          }else{
            Dialog.alert({
              title: '温馨提示',
              message: `还没有设置${this.qrCodeTypeObj[this.itemObj.id]}码，请先设置！或者点击页面中的设置。`,
              messageAlign: 'left',
              theme: 'round-button',
              confirmButtonText: '确定设置'
            }).then(() => {
              this.verify_code = Math.floor(Math.random() * (999999 - 100000 + 1) + 100000)
            })
          }
          
        }
      }
    },

    onSelect(item, index) {
      console.log('下标', index)
      // 默认情况下点击选项时不会自动收起
      // 可以通过 close-on-click-action 属性开启自动收起
      this.showAction = false
      Toast(item.name)
    },
    replay() {
      if (this.verify_code) {
        Dialog.confirm({
          title: '温馨提示',
          message: `已设置过：${this.qrCodeTypeObj[this.itemObj.id]}码，确定继续设置码？`
        })
          .then(() => {
            // on close
            this.verify_code = Math.floor(Math.random() * (999999 - 100000 + 1) + 100000)
            Toast('已设置成功！请先点击确定使用')
            this.isCanUseCode = false
          })
          .catch(() => {
            // on cancel
          })
      } else {
        // 生成码
        this.verify_code = Math.floor(Math.random() * (999999 - 100000 + 1) + 100000)
      }
    },
    async useCode() {
      let params = {
        job_id: this.$route.query.job_id,
        // 统一的多个码
        baodaocode: this.verify_code,
        // 码的标识
        type: this.typeList[this.type]
      }
      if (this.itemObj.id == '5') {
        if (this.hannelRadio === '') {
          Toast.fail('请选择渠道')
          return
        }
        try {
          await this.$api.company.setchannelid({
            ChannelId: this.hannelRadio,
            JobID: this.needObj.id
          })
        } catch {
          Toast.fail('绑定渠道失败')
          return
        }
      }
      const res = await reqUpdateBdCode(params)
      if (res.code === 200) {
        Toast.success('使用成功，凌晨十二点自动失效，并清除！')
        this.isCanUseCode = true
      }
    },

    toCreateQrCode() {
      console.log('二维码')
      this.$router.push({
        path: '/myCompany/rollCallQrCode',
        query: {
          // 将传递的对象解析为字符串
          itemObj: JSON.stringify(this.itemObj),
          job_id: this.$route.query.job_id
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page_staffRollCall {
  width: 100%;
  .channelBox {
    padding: 8px;
    .list {
      .item {
        padding: 12px;
        background-color: #fff;
        border-radius: 8px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;
        .left {
          width: 250px;
          .top,
          .bottom {
            display: flex;
            align-items: center;
            font-size: 14px;
            flex-wrap: wrap;
          }
          .top {
            margin-bottom: 4px;
          }
        }
      }
    }
  }
  .replay-icon {
    margin-left: 10px;
  }
  .van-cell--large {
    padding-right: 150px;
  }
  .codeDiv {
    position: relative;
    .useBtn {
      position: absolute;
      background: rgb(54, 215, 183);
      top: 1px;
      color: #fff;
      right: 5px;
    }
  }
}
</style>
